package com.bw.module_cinema.search

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bw.lib_storage.db.entity.SearchEntity
import com.bw.module_cinema.databinding.ItemSearchHistoryBinding

class SearchHistoryAdapter () : RecyclerView.Adapter<SearchHistoryAdapter.HistoryViewHolder>() {

    interface OnDeleteClickListener {
        fun onDeleteClick(entity: SearchEntity)
    }
    
    interface OnItemClickListener {
        fun onItemClick(entity: SearchEntity)
    }

    private var deleteListener : OnDeleteClickListener? = null
    private var itemListener : OnItemClickListener? = null

    fun setOnDeleteClickListener(listener: OnDeleteClickListener){
        this.deleteListener = listener
    }
    
    fun setOnItemClickListener(listener: OnItemClickListener){
        this.itemListener = listener
    }

    private val list = ArrayList<SearchEntity>()

    fun setData(mList: List<SearchEntity>){
        list.clear()
        list.addAll(mList)
        notifyDataSetChanged()
    }

    class HistoryViewHolder(
        val binding: ItemSearchHistoryBinding
    ) : RecyclerView.ViewHolder(binding.root)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryViewHolder {
        val binding = ItemSearchHistoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return HistoryViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
        val item = list[position]
        holder.binding.search = item

        // 点击整个item
        holder.itemView.setOnClickListener {
            itemListener?.onItemClick(item)
        }
        
        // 点击删除按钮
        holder.binding.ivDelete.setOnClickListener {
            deleteListener?.onDeleteClick(item)
        }
    }
}